<template>
  <div class="login-container">
    <div class="login-card">
      <div class="logo-section">
        <img src="@/assets/logo.png" alt="俊和 CHUN Wo" class="logo" />
      </div>
      <div class="button-section">
        <button type="button" @click="handleMs365Login" class="ms365-btn">
          Sign in with Microsoft 365
        </button>
      </div>
      <div v-if="error" class="error">{{ error }}</div>
      <div v-if="error" class="debug-info">
        <p><strong>调试信息:</strong></p>
        <pre>{{ debugInfo }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user';
import http from '@/api/http';

const error = ref('');
const debugInfo = ref('');
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

onMounted(() => {
  console.log('🔐 登录页面加载');
  console.log('📍 当前URL:', window.location.href);
  console.log('👤 当前登录状态:', {
    isLogin: userStore.isLogin,
    hasToken: !!userStore.token,
    username: userStore.username
  });
  
  debugInfo.value = `当前URL: ${window.location.href}\n登录状态: ${userStore.isLogin}\n用户名: ${userStore.username}`;
  
  // 如果已经登录，检查是否有重定向参数
  if (userStore.isLogin) {
    console.log('✅ 用户已登录');
    const redirectPath = route.query.redirect as string;
    if (redirectPath) {
      console.log('🔄 跳转到用户原本想访问的页面:', redirectPath);
      router.push(redirectPath);
    } else {
      console.log('🏠 跳转到主页');
      router.push('/');
    }
  }
});

async function handleMs365Login() {
  try {
    console.log('🔧 开始MS365登录流程...');
    error.value = '';
    debugInfo.value += '\n开始MS365登录...';
    
    // 获取用户原本想访问的页面
    const redirectPath = route.query.redirect as string || '/';
    console.log('🎯 用户原本想访问的页面:', redirectPath);
    debugInfo.value += '\n用户原本想访问的页面: ' + redirectPath;
    
    // 直接跳转到后台API，让浏览器处理重定向
    // 这样可以避免CORS问题，因为浏览器会直接跟随302重定向
    // 使用相对路径，通过Vite代理转发到后台
    const apiUrl = `/auth/ms-365-auth/authorize?redirect=${encodeURIComponent(redirectPath)}`;
    console.log('🔄 跳转到后台API:', apiUrl);
    debugInfo.value += '\n跳转到后台API: ' + apiUrl;
    
    // 使用 window.location.href 直接跳转，让浏览器处理重定向
    window.location.href = apiUrl;
    
  } catch (err: any) {
    console.error('❌ MS365登录失败:', err);
    error.value = err.message || '登录失败，请重试';
    debugInfo.value += `\n登录失败: ${err.message}`;
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
  background-image: url('@/assets/bg-login-img.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(2px);
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 1rem 1rem;
  text-align: center;
  max-width: 420px;
  width: 90%;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
  flex: 1 1 auto;
}

.logo-section {
  margin-bottom: 32px;
}

.logo {
  max-width: 320px;
  width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
}

.button-section {
  margin-bottom: 16px;
}

.ms365-btn {
  background: #0d6efd;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 24px;
  font-size: 16px;
  font-weight: 500;
  font-family: Noto Sans TC, Noto Sans SC, Roboto, sans-serif;
  cursor: pointer;
  width: 100%;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(13, 110, 253, 0.3);
}

.ms365-btn:hover {
  background: #0b5ed7;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(13, 110, 253, 0.4);
}

.ms365-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 120, 212, 0.3);
}

.error {
  color: #d32f2f;
  background: #ffebee;
  border: 1px solid #ffcdd2;
  border-radius: 6px;
  padding: 12px;
  margin-top: 16px;
  font-size: 14px;
}

.debug-info {
  margin-top: 1rem;
  padding: 1rem;
  background: #f5f5f5;
  border-radius: 4px;
  text-align: left;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.debug-info pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 32px 24px;
    margin: 20px;
  }
  
  .logo {
    max-width: 280px;
  }
  
  .ms365-btn {
    padding: 14px 20px;
    font-size: 15px;
  }
}
</style> 